﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;

namespace Arch.Common.IoC
{
    public class ArchUnityDependencyContainer : IDependencyContainer
    {
        #region Container creation
        private static IUnityContainer _mainContainer;

        protected static IUnityContainer Container
        {
            get
            {
                if (_mainContainer == null)
                {
                    throw new InvalidOperationException("Unity Container not initilized");
                }
                return _mainContainer;
            }
            set { _mainContainer = value; }
        }

        public static IUnityContainer InitContainer(IUnityContainer container)
        {
            Container = container;
            try
            {
                var mappings = Container.Resolve<IDependencyContainer>();
                mappings.Init();
            }
            catch (ResolutionFailedException ex)
            {
                throw new InvalidOperationException("IDependencyContainer not registred to unity", ex);
            }
            return container;
        }

        #endregion Container creation

        public bool IsLoaded { get; set; }

        public virtual void Init()
        {
            Loading(Container);
            LoadExtensions(Container);
            RegisterDefaults(Container);
            RegisterTypes(Container);
            AutoRegister(Container);
            Loaded(Container);
            IsLoaded = true;
        }

        protected virtual void LoadExtensions(IUnityContainer container)
        {
        }

        protected virtual void RegisterDefaults(IUnityContainer container)
        {
            Container.RegisterInstance<IDependencyContainer>(this);
        }

        public virtual void Loaded(IUnityContainer container)
        {

        }

        public virtual void Loading(IUnityContainer container)
        {


        }

        public virtual void RegisterTypes(IUnityContainer container)
        {

        }

        public virtual void AutoRegister(IUnityContainer container)
        {

        }

        #region Auto register tools
        protected Type GetMappedType(IUnityContainer container, string typeName)
        {
            return container.Registrations.FirstOrDefault(r => r.MappedToType.Name.StartsWith(typeName)).MappedToType;
        }

        protected virtual List<Type> GetLayerTypes(IUnityContainer container, string baseClassName)
        {
            Type projectRepositoryType = GetMappedType(container, baseClassName);
            return GetLayerTypes(projectRepositoryType);
        }

        protected virtual List<Type> GetLayerTypes(Type baseType, Assembly targetAssembly = null)
        {
            string typeName = baseType.Name.Split('`').FirstOrDefault();

            return (targetAssembly ?? baseType.Assembly).GetTypes().Where(type =>
            {
                if (type.IsAbstract) return false;
                if (type.BaseType != null)
                {
                    while (true)
                    {
                        if (type.BaseType.Equals(typeof(object))) break;
                        var split = type.BaseType.Name.Split('`');
                        if (split.Count() > 1 && split.FirstOrDefault() == typeName)
                            return true;
                        else
                            type = type.BaseType;
                    }
                }
                return false;
            }).ToList();
        }

        protected virtual void AutoRegisterTypes(IUnityContainer container, Type baseInterfaceType, ICollection<Type> types, Action<Type, Type> applyConfiguration = null)
        {
            foreach (var type in types)
            {
                container.RegisterType(type, type);

                var genericInterfaceType = baseInterfaceType.MakeGenericType(
                    new Type[] { type.BaseType.GetGenericArguments()[0] });

                container.RegisterType(genericInterfaceType, type);

                var obj = type.GetInterfaces().Where(i => genericInterfaceType.IsAssignableFrom(i) && !i.Equals(genericInterfaceType));
                var interfaceType = obj.FirstOrDefault();
                if (interfaceType != null)
                    container.RegisterType(interfaceType, type);


                if (applyConfiguration != null)
                    applyConfiguration(interfaceType, type);
            }
        }
        #endregion

        #region Resolvers
        public object GetInstance(Type t, string name)
        {
            return HandledGetInstance(() => Container.Resolve(t, name));
        }

        public object GetInstance(Type t)
        {
            return HandledGetInstance(() => Container.Resolve(t));
        }

        public T GetInstance<T>()
        {
            return HandledGetInstance(() => Container.Resolve<T>());
        }

        public T GetInstance<T>(string name)
        {
            return HandledGetInstance(() => Container.Resolve<T>(name));
        }

        protected T HandledGetInstance<T>(Func<T> call)
        {
            try
            {
                return call();
            }
            catch(Exception ex)
            {
                throw new ActivationException("Error in container, see InnerException", ex);
            }
        }

        public void BuildUp<T>(T instance)
        {
            Container.BuildUp<T>(instance);
        }

        public void BuildUp(object instance)
        {
            try
            {
                Container.BuildUp(instance.GetType(), instance);
            }
            catch(Exception ex)
            {
                throw new ActivationException();
            }
        }

        protected void HandledBuildUp<T>(Action call)
        {
            try
            {
                call();
            }
            catch (Exception ex)
            {
                throw new ActivationException("Error in container, see InnerException", ex);
            }
        }

        #endregion
    }
}
